package me.gavin.base

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.webkit.WebView
import androidx.core.content.getSystemService
import me.gavin.BuildConfig
import me.gavin.di.remoteModule
import me.gavin.di.reposModule
import me.gavin.di.viewModelModule
import me.gavin.util.CrashHandler
import me.gavin.util.ImageLoader
import me.gavin.util.log
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidFileProperties
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import java.lang.ref.WeakReference

/**
 * 如果使用到了Application替换技术，( hotpatch/dex加壳/... )
 * 在 ContentProvider 中 getContext() 获得的是 ProxyApplication，而不是真正的Application
 */
class Gavin : ContentProvider() {

    override fun onCreate(): Boolean {

        "onCreate - Gavin".log()

        gavin = this
        app = context as Application

        startKoin {
            androidLogger()
            androidContext(app)
            androidFileProperties()
            // modules(viewModelModule, reposModule, remoteModule)
            koin.loadModules(listOf(viewModelModule, reposModule, remoteModule))
            koin.createRootScope()
        }

        CrashHandler.init()
        ImageLoader.init()
        AutoSizer.fixInvalidOnSplit()

        if (app.packageName == processN && BuildConfig.DEBUG) {
            WebView.setWebContentsDebuggingEnabled(true)
        }

        app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {
                sResumeActivitiesCount++
                currentActivity = WeakReference(activity)
            }

            override fun onActivityPaused(activity: Activity) {
                sResumeActivitiesCount--
            }

            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        })

        return true
    }

    private val processN
        get() = context!!.getSystemService<ActivityManager>()
                ?.runningAppProcesses
                ?.find { it.pid == android.os.Process.myPid() }
                ?.processName


    override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
    override fun getType(uri: Uri): String? = null
    override fun insert(uri: Uri, values: ContentValues?): Uri? = null
    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?) = 0
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = 0

    companion object {
        lateinit var gavin: Gavin
            private set
        lateinit var app: Application
            private set

        var currentActivity: WeakReference<Activity>? = null
            private set

        private var sResumeActivitiesCount = 0
        val isForeground get() = sResumeActivitiesCount > 0
    }

}